<template>
  <div class="chapter-detail">
    <h2>具体章节内容编辑</h2>
    <CourseChoose 
      :courseInfo="courseInfo || null" 
      :autoQueryParams="autoQueryParams"
      @course-selected="onCourseSelected" 
    />
    <div v-if="selectedCourse" class="chapter-select-section">
      <label>选择章节：</label>
      <select v-model="selectedChapterId">
        <option value="" disabled>请选择章节</option>
        <option v-for="(chapter, index) in chapters" :key="index" :value="index">
          第{{ index + 1 }}章 {{ chapter.content }}
        </option>
      </select>
    </div>
    
    <!-- 章节信息展示区域 -->
    <div v-if="selectedChapter" class="chapter-info-section">
      <h3>章节信息（只读）</h3>
      <div class="info-grid">
        <div class="info-item">
          <label>课程内容：</label>
          <div class="info-content">{{ selectedChapter.content }}</div>
        </div>
        <div class="info-item">
          <label>教学方法：</label>
          <div class="info-content">{{ selectedChapter.method }}</div>
        </div>
        <div class="info-item">
          <label>支撑的课程目标：</label>
          <div class="info-content">{{ selectedChapter.goal }}</div>
        </div>
        <div class="info-item">
          <label>思政元素：</label>
          <div class="info-content">{{ selectedChapter.political_element }}</div>
        </div>
        <div class="info-item">
          <label>学时安排：</label>
          <div class="info-content">{{ selectedChapter.period }} 学时</div>
        </div>
      </div>
    </div>

    <div v-if="selectedChapter" class="chapter-edit-section">
      <h3>章节教案编辑</h3>
      <div class="form-row">
        <label>知识目标：</label>
        <textarea v-model="form.knowage_goal" rows="3" placeholder="请输入知识目标，支持换行"></textarea>
      </div>
      <div class="form-row">
        <label>能力目标：</label>
        <textarea v-model="form.ability_goal" rows="3" placeholder="请输入能力目标，支持换行"></textarea>
        <button class="ai-btn">AI生成</button>
      </div>
      <div class="form-row">
        <label>情感与价值观目标：</label>
        <textarea v-model="form.EAV_goal" rows="3" placeholder="请输入情感与价值观目标，支持换行"></textarea>
        <button class="ai-btn">AI生成</button>
      </div>
      <div class="form-row">
        <label>学习内容：</label>
        <input v-model="form.study_content" placeholder="请输入学习内容" />
      </div>
      <div class="form-row">
        <label>重点：</label>
        <input v-model="form.important" placeholder="请输入本章重点" />
      </div>
      <div class="form-row">
        <label>难点：</label>
        <input v-model="form.difficult" placeholder="请输入本章难点" />
      </div>
      <div class="form-row">
        <label>课堂导入内容：</label>
        <textarea v-model="form.lead_in_content" rows="6" placeholder="请输入课堂导入内容，支持换行，如使用AI生成，可以先在此输入提示词，再点击AI生成"></textarea>
        <button class="ai-btn">AI生成</button>
      </div>
      <div class="form-row">
        <label style="min-width:120px;">导入时长：</label>
        <input v-model.number="form.lead_in_duration" type="number" min="0" style="width: 80px;" placeholder="分钟" />
      </div>
      <div class="form-row">
        <label>课堂教学内容：</label>
        <textarea v-model="form.content_in_class" rows="4" placeholder="请输入课堂教学内容，支持换行，如使用AI生成，可以先在此输入提示词，再点击AI生成"></textarea>
        <button class="ai-btn">AI生成</button>
      </div>
      <div class="form-row">
        <label>课堂小结内容：</label>
        <textarea v-model="form.summary_content" rows="6" placeholder="请输入课堂小结内容，支持换行，如使用AI生成，可以先在此输入提示词，再点击AI生成"></textarea>
        <button class="ai-btn">AI生成</button>
      </div>
      <div class="form-row">
        <label style="min-width:120px;">小结时长：</label>
        <input v-model.number="form.summary_duration" type="number" min="0" style="width: 80px;" placeholder="分钟" />
      </div>
      <div class="form-row">
        <label>教学工具资源：</label>
        <textarea v-model="form.tool_and_resource" rows="2" placeholder="请输入教学工具或资源，支持换行"></textarea>
      </div>
      <div class="form-row">
        <label>课程实践：</label>
        <textarea v-model="form.practice" rows="2" placeholder="请输入课程实践，支持换行"></textarea>
      </div>
      <div class="form-row">
        <label>复习思考：</label>
        <textarea v-model="form.review" rows="2" placeholder="请输入复习思考，支持换行"></textarea>
      </div>
      <div class="form-row">
        <label>教学反思：</label>
        <textarea v-model="form.reflect" rows="2" placeholder="请输入教学反思，支持换行"></textarea>
      </div>
      <div class="form-row">
        <button class="save-btn" @click="saveDetail">保存</button>

        <button class="next-item-btn" @click="handleNext">下一项</button>
      </div>
    </div>
  </div>
</template>

<script>
import CourseChoose from './CourseChoose.vue';
import { courseApi } from '../api/index.js';

export default {
  name: 'CourseChapterDetail',
  components: { CourseChoose },
  props: {
    courseInfo: {
      type: Object,
      default: null
    },
    autoQueryParams: {
      type: Object,
      default: null
    }
  },
  emits: ['next-step'],
  data() {
    return {
      selectedCourse: null,
      chapters: [], // 从接口获取的章节信息
      selectedChapterId: '',
      form: {
        knowage_goal: '',
        ability_goal: '',
        EAV_goal: '',
        study_content: '',
        important: '',
        difficult: '',
        lead_in_content: '',
        lead_in_duration: '',
        content_in_class: '',
        summary_content: '',
        summary_duration: '',
        tool_and_resource: '',
        practice: '',
        review: '',
        reflect: '',
      },
    };
  },
  computed: {
    selectedChapter() {
      if (this.selectedChapterId !== '' && this.chapters.length > 0) {
        return this.chapters[this.selectedChapterId];
      }
      return null;
    },
  },
  watch: {
    // 监听props变化，如果有课程信息则自动选择
    courseInfo: {
      handler(newCourseInfo) {
        console.log('CourseChapterDetail watch courseInfo:', { newCourseInfo });
        if (newCourseInfo && Object.keys(newCourseInfo).length > 0 && newCourseInfo.id) {
          this.onCourseSelected(newCourseInfo);
        } else {
          // 如果没有有效的课程信息，清空状态
          this.selectedCourse = null;
          this.chapters = [];
          this.selectedChapterId = '';
          this.resetForm();
        }
      },
      immediate: true
    },
    // 监听章节选择变化，自动加载章节详细信息
    selectedChapterId: {
      handler(newChapterId) {
        if (newChapterId !== '' && this.selectedCourse && this.selectedCourse.id) {
          this.loadChapterDetail();
        } else {
          // 清空表单
          this.resetForm();
        }
      },
      immediate: false
    }
  },
  methods: {
    async onCourseSelected(course) {
      console.log('CourseChapterDetail onCourseSelected:', { course });
      this.selectedCourse = course;
      this.selectedChapterId = '';
      this.chapters = [];
      this.resetForm();
      
      if (course && course.id) {
        try {
          // 调用接口查询章节信息
          const response = await courseApi.queryCourseContent(course.id);
          if (response && response.data) {
            this.chapters = response.data.content_relation;
          }
        } catch (error) {
          console.error('获取章节信息失败：', error);
          alert('获取章节信息失败，请重试');
        }
      }
    },

    // 加载章节详细信息
    async loadChapterDetail() {
      if (!this.selectedCourse || !this.selectedCourse.id || this.selectedChapterId === '') {
        return;
      }

      try {
        const response = await courseApi.queryChapterDetail(
          this.selectedCourse.id, 
          this.selectedChapterId
        );
        
        if (response && response.data) {
          // 将接口返回的数据填充到表单中
          this.form = {
            knowage_goal: response.data.knowage_goal || '',
            ability_goal: response.data.ability_goal || '',
            EAV_goal: response.data.EAV_goal || '',
            study_content: response.data.study_content || '',
            important: response.data.important || '',
            difficult: response.data.difficult || '',
            lead_in_content: response.data.lead_in_content || '',
            lead_in_duration: response.data.lead_in_duration || '',
            content_in_class: response.data.content_in_class || '',
            summary_content: response.data.summary_content || '',
            summary_duration: response.data.summary_duration || '',
            tool_and_resource: response.data.tool_and_resource || '',
            practice: response.data.practice || '',
            review: response.data.review || '',
            reflect: response.data.reflect || '',
          };
          // console.log('加载章节详细信息成功：', this.form);
        }
      } catch (error) {
        console.error('加载章节详细信息失败：', error);
        // 如果查询失败，可能是新章节，清空表单
        this.resetForm();
      }
    },

    // 重置表单
    resetForm() {
      this.form = {
        knowage_goal: '',
        ability_goal: '',
        EAV_goal: '',
        study_content: '',
        important: '',
        difficult: '',
        lead_in_content: '',
        lead_in_duration: '',
        content_in_class: '',
        summary_content: '',
        summary_duration: '',
        tool_and_resource: '',
        practice: '',
        review: '',
        reflect: '',
      };
    },

    // 保存章节详细信息
    async saveDetail() {
      if (!this.selectedCourse || !this.selectedCourse.id || this.selectedChapterId === '') {
        alert('请先选择课程和章节');
        return;
      }

      try {
        const params = {
          courseId: this.selectedCourse.id,
          chapterId: this.selectedChapterId,
          ...this.form
        };

        const response = await courseApi.saveChapterDetail(params);
        
        if (response && response.success===0) {
          alert('保存成功！');
        } else {
          alert('保存失败：' + (response.message || '未知错误'));
        }
      } catch (error) {
        console.error('保存章节详细信息失败：', error);
        alert('保存失败，请重试');
      }
    },



    // 跳转到下一项（不保存）
    handleNext() {
      console.log('CourseChapterDetail handleNext:', { selectedCourse: this.selectedCourse });
      
      // 检查是否有选中的课程
      if (!this.selectedCourse || !this.selectedCourse.id) {
        alert('请先选择课程');
        return;
      }
      
      // 构建要传递的课程信息，包含自动查询所需的参数
      const courseInfo = {
        ...this.selectedCourse,
        grade: this.selectedCourse.grade || this.selectedCourse.year,
        major: this.selectedCourse.major || this.selectedCourse.majorName,
        courseId: this.selectedCourse.courseId || this.selectedCourse.id,
        courseName: this.selectedCourse.courseName || this.selectedCourse.name
      }
      
      // 触发下一项事件
      this.$emit('next-step', 'course-6', courseInfo);
    },
  },
};
</script>

<style scoped>
.chapter-detail {
  padding: 24px;
  color: #333; /* 设置默认文字颜色为深灰色 */
}

.chapter-detail h2 {
  color: #333; /* 确保主标题颜色正常 */
}
.chapter-select-section {
  margin-top: 20px;
  margin-bottom: 24px;
}

.chapter-select-section label {
  color: #333; /* 确保选择章节标签颜色正常 */
}

.chapter-select-section select {
  color: #333; /* 确保选择框文字颜色正常 */
}
.chapter-info-section {
  margin-top: 24px;
  margin-bottom: 24px;
  padding: 20px;
  background-color: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #e9ecef;
}
.chapter-info-section h3 {
  margin-top: 0;
  margin-bottom: 16px;
  color: #333; /* 确保章节信息标题颜色正常 */
  font-size: 18px;
}
.info-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16px;
}
.info-item {
  display: flex;
  flex-direction: column;
  gap: 4px;
}
.info-item label {
  font-weight: 600;
  color: #333; /* 确保信息项标签颜色正常 */
  font-size: 14px;
}
.info-content {
  padding: 8px 12px;
  background-color: white;
  border: 1px solid #dee2e6;
  border-radius: 4px;
  min-height: 20px;
  color: #333; /* 确保信息内容颜色正常 */
}
.chapter-edit-section {
  margin-top: 24px;
  border-top: 1px solid #eee;
  padding-top: 20px;
  max-width: 1200px;
}
.chapter-edit-section h3 {
  margin-top: 0;
  margin-bottom: 20px;
  color: #333; /* 确保编辑区域标题颜色正常 */
  font-size: 18px;
}
.form-row {
  display: flex;
  align-items: flex-start;
  margin-bottom: 16px;
  gap: 8px;
}
.form-row label {
  min-width: 120px;
  font-weight: 500;
  color: #333; /* 确保表单标签颜色正常 */
}
.form-row input,
.form-row textarea,
.form-row select {
  flex: 1;
  padding: 4px 8px;
  font-size: 15px;
  color: #333; /* 确保输入框文字颜色正常 */
}
.form-row textarea {
  resize: vertical;
}
.ai-btn {
  margin-left: 8px;
  background: #f3f6ff;
  border: 1px solid #409eff;
  color: #409eff;
  border-radius: 4px;
  padding: 4px 12px;
  cursor: pointer;
}
.ai-btn:hover {
  background: #e6f0ff;
}
.save-btn {
  background: #409eff;
  color: #fff;
  border: none;
  padding: 8px 28px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 16px;
}
.save-btn:hover {
  background: #337ecc;
}
.next-chapter-btn {
  background: #67c23a;
  color: #fff;
  border: none;
  padding: 8px 28px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 16px;
  margin-left: 10px;
}
.next-chapter-btn:hover {
  background: #5daf34;
}
.next-item-btn {
  background: #e6a23c;
  color: #fff;
  border: none;
  padding: 8px 28px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 16px;
  margin-left: 10px;
}
.next-item-btn:hover {
  background: #cf9236;
}
</style>